package com.czd.support.controller;

import com.czd.support.model.Answers;
import com.czd.support.model.Manager;
import com.czd.support.service.AnswerService;
import com.czd.support.service.QuestionService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;

/**
 * Created with IntelliJ IDEA.
 * Author: Jerry.hu
 * Create: Jerry.hu (2014-10-03 15:33)
 * Description:
 * To change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping(value = "/answer")
public class AnswersController extends BaseController {

    @Autowired
    private AnswerService answerService;
    @Autowired
    private QuestionService questionService;

    /**
     * 答案列表页
     * @param model
     * @param request
     * @param answers
     * @return
     */
    @RequestMapping(value = {"","/","list"},method = RequestMethod.GET)
    public String list(Model model,HttpServletRequest request,Answers answers,@RequestParam(value = "pageNo",defaultValue = "1") int pageNo){
        answers.setPageNo(pageNo);
        model.addAttribute("paginate",answerService.queryForPaginate(answers));
        return "answer/list";
    }

    /**
     * 新增题目控制器
     * @return
     */
    @RequestMapping(value = "/add",method = RequestMethod.GET)
    public String add(){
        return "answer/add";
    }

    /**
     * 录入题目 拦截
     * @param answers
     * @param request
     * @return
     */
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public String save(Answers answers,HttpServletRequest request,Model model){
        Manager manager = this.getSesionUser(request);
        answers.setCreater(manager.getUserCode());
        answers.setUpdater(manager.getUserCode());
        if(StringUtils.isBlank(answers.getAnswersContent())){
            return  error(model, "操作提示", "答案不许为空");
        }
        if(answerService.insert(answers)){
            return "redirect:/answer/"+answers.getId()+"/details";
        }
        return  error(model, "操作提示", "答案录入失败");
    }

    /**
     * 题目详情页 拦截
     * @param id
     * @param model
     * @return
     */
    @RequestMapping(value = "/{id}/details",method = RequestMethod.GET)
    public String view(@PathVariable int id,Model model){
        Answers answer = answerService.findById(id);
        if(answer != null){
            model.addAttribute("answer",answer);
            model.addAttribute("questionList", questionService.queryQuestionByAId(answer.getId()));
            return "answer/details";
        }
        return error(model,"信息不存在","题目不存在");
    }

}
